
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Text.RegularExpressions;
using System.Xml;

using Swaf;
using Swaf.BizObj;
using Swaf.Messaging;

namespace Swaf.DataAccess.Messaging
{
	/// <summary>
	/// Summary description for MessageBizObjFormatter.
	/// </summary>
	public class MessageBizObjFormatter : IDataFormatter
	{
		public MessageBizObjFormatter()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		protected string m_bizObjSpec;
		protected IApplication m_app;
		protected MessagingDataResponse m_resp;

		public MessageBizObjFormatter(Match mr, object[] extraInfo)
		{
			if(extraInfo != null && extraInfo.Length > 0 && extraInfo[0] is MessagingDataResponse)
			{		
				m_resp = (MessagingDataResponse)extraInfo[0];
				m_app = Application.currentApp;
				m_bizObjSpec = mr.Groups[1].Value;
			}
		}
		#region IDataFormatter Members

		public object format()
		{
			IBizObjList lst = null;
		
			if(m_resp != null) 
			{
				string rspTxt = m_resp.getText();
				rspTxt=MessagingSystemBase.CheckForEncrypt(rspTxt);
				if (rspTxt.StartsWith("<RuleCallResults>"))
				{
					XmlDocument doc = new XmlDocument();
					doc.LoadXml(rspTxt);
					BasicResults rc = BasicResults.createFromXml(doc.DocumentElement);
					return rc.CallResults;
				}
				else
				{
					try 
					{
						lst = m_app.bizObjMgr.createSource(SourceType.XmlSource, rspTxt).getList(m_bizObjSpec, m_bizObjSpec);
					}
					catch(Exception e)
					{
						throw new MessagingDataAccessException(
							String.Format("Unable to format Messaging Response.\n----- The Message Contained ----------\n{0}--------------------------------------", rspTxt), e);
					}
				}
			}
		
			return lst;
		}

		#endregion

	}
}
